/**
 * 路由内的任务
 *
 * @author bian
 * @createDate 2016.9.8
 */
var models = require("../models/index").models;
var Data = models.Data;

var Task = (function (){

    var checkPlan = function(sockets,state){

        var p;
        p = new Promise(function(resolve,reject){
           Data.findAll({
               where:{
                   type : "plan"
               }
           }).then(function(plans){
               var s;                // get socket
               for(s of sockets){
                   if(s.name === "Intel"){
                       break;
                   }
               }

               for(var pl of plans){
                   sendPlan(pl.equipment,s,pl.type,pl.value,state);   // hook plan
               }

               resolve(true);
           });
        });
        return p;
    };

    var sendPlan = function(equipment,socket,type,value,state){
        getSendFunc()[equipment](socket,type,value,state);
    };

    var getSendFunc = () => {
        return {
            "intelBody" : sendIntelBodyPlan
        }
    };

    var sendIntelBodyPlan = (socket,type,value,state) => {
        if(!socket) return;
        value = JSON.parse(value);
        if(value.target === "intelPatch"){      // if the target is Patch
            if(state.value == "0"){             // if people is not in home
                socket.emit("intelPatch",{
                    type : "state",
                    value : value.result.off.toString()
                });
            }else if(state.value == "1"){       // if people is in home
                socket.emit("intelPatch",{
                    type : "state",
                    value : value.result.on.toString()
                });
            }
        }
    };

    return {
        sendPlan,
        checkPlan
    };
}());

module.exports = Task;